/// @tags:
#include <cstdio>
#include <functional>
#include <iostream>
#include <numeric>

using std::cin, std::cout, std::endl;

namespace BlueQuantum {

constexpr int maxn = 2e5 + 5;

int a[maxn], col[maxn];
bool vis[maxn];

int main() {
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    std::fill(vis + 1, vis + n + 1, false);
    std::fill(col + 1, col + n + 1, 0);
    for (int i = 1; i <= n; ++i) {
      cin >> a[i];
    }
    int cnt = 0, ccnt = 0;
    for (int i = 1; i <= n; ++i) {
      if (!vis[i]) {
        int u = a[i];
        ++ccnt;
        while (u != i) {
          col[u] = ccnt;
          vis[u] = true;
          u = a[u];
        }
        col[i] = ccnt;
        vis[i] = true;
        ++cnt;
      }
    }
    int ans = 1;
    for (int i = 1; i < n; ++i) {
      if (i + 1 == a[i] || i == a[i + 1]) ans = std::min(ans, -1);
      if (col[i] == col[i + 1]) ans = std::min(ans, -1);
    }
    cout << ans + n - cnt << '\n';
  }
  return 0;
}

}  // namespace BlueQuantum

int main() {
#ifndef ONLINE_JUDGE
#ifdef LOCAL
  freopen("/tmp/CodeTmp/testdata.in", "r", stdin);
  freopen("/tmp/CodeTmp/testdata.out", "w", stdout);
#else
  freopen("D. Lucky Permutation.in", "r", stdin);
  freopen("D. Lucky Permutation.out", "w", stdout);
#endif
#endif

  std::ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
  return BlueQuantum::main();
}
